package com.itkjb.leisurely.center.config.authentication;


import com.itkjb.leisurely.authentication.core.common.config.BaseAuthenticationConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.cors.CorsUtils;

/**
 * Copyright (C), 2018-2099
 * @FileName: SecurityConfig
 * @Author:   lix
 * @Date:     2019-05-14 18:53
 * @Description: security 配置
 * @Version: V1.0.0
 */
@Slf4j
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private BaseAuthenticationConfig baseAuthenticationConfig;



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.debug("Using SecurityConfig configure(HttpSecurity). " );
        // 调用父类配置
        baseAuthenticationConfig.configure(http);
        http.cors()
                // .disable().authorizeRequests()
                .and().csrf().disable()
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers("/**").authenticated()
                .and()
                    .headers().frameOptions().sameOrigin() // 将response的header中的X-Frame-Options项的值改为SAMEORIGIN

        ;
        // http.apply(dingDingAuthenticationSecurityConfig);
        // http.apply(futaiAuthenticationSecurityConfig);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        baseAuthenticationConfig.configure(web);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
